package com.example.qxfw.qxybzz.service.Impl;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.qxfw.common.dmgis.edit.TextEdit;
import com.example.qxfw.common.dmgis.analysis.GridAnalyse;
import com.example.qxfw.common.dmgis.constant.ContourMapType;
import com.example.qxfw.common.dmgis.constant.InterType;
import com.example.qxfw.common.dmgis.entity.ContourSetting;
import com.example.qxfw.common.dmgis.layer.*;
import com.example.qxfw.common.dmgis.mapper.ContourSettingMapper;
import com.example.qxfw.common.dmgis.open.OpenProject;
import com.example.qxfw.common.dmgis.vo.AInfGradeVo;
import com.example.qxfw.common.dmgis.vo.PointVo;
import com.example.qxfw.common.util.FileUtil;
import com.example.qxfw.common.util.MongoUtil;
import com.example.qxfw.qxybzz.entity.ContourMap;

import com.example.qxfw.common.dmgis.entity.EqProjectConfig;
import com.example.qxfw.common.dmgis.mapper.EqProjectConfigMapper;
import com.example.qxfw.qxybzz.service.ContourMapService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

@Service
public class ContourMapServiceImpl implements ContourMapService {
    @Autowired
    private  GridAnalyse gridAnalyse;

    @Autowired
    private OpenProject openProject;

    @Autowired
    private EqProjectConfigMapper projectConfigMapper;

    @Autowired
    private ContourSettingMapper contourSettingMapper;

    @Autowired
    @Qualifier("mongoPrimaryTemplate")
    private MongoTemplate mongoTemplate;


    @Override
    public ContourMap cenerateContourMaps(List<PointVo> points, String textContent,InterType interType, ContourMapType contourMapType) {
        ContourMap contourMap = null;
        EqProjectConfig projectConfig = projectConfigMapper.selectOne(new LambdaQueryWrapper<>());
        List<ContourSetting> contourSettings;
        if (contourMapType.getName().contains(",")){
            String[] split = contourMapType.getName().split(",");
            LambdaQueryWrapper<ContourSetting> wrapper = new LambdaQueryWrapper<ContourSetting>().
                    eq(ContourSetting::getElementtype, split[0]).
                    or().
                    eq(ContourSetting::getElementtype, split[1]).
                    orderByAsc(ContourSetting::getElementvalue);
            contourSettings=contourSettingMapper.selectList(wrapper);
        }else {
            contourSettings= contourSettingMapper.selectList(new LambdaQueryWrapper<ContourSetting>().
                    eq(ContourSetting::getElementtype, contourMapType.getName()).
                    orderByAsc(ContourSetting::getElementvalue));
        }


        if (projectConfig==null||contourSettings.isEmpty()){
            return null;
        }
        List<AInfGradeVo> aInfGradeVos = contourSettings.stream().map(item -> new AInfGradeVo(item.getElementcolor(), item.getElementvalue())).collect(Collectors.toList());
        ReentrantLock lock=new ReentrantLock();
        String imgPath;
        try {
            lock.lock();
            if (textContent!=null&&!textContent.isEmpty()){
                TextEdit.updateTextContent(projectConfig.getTextPath(),projectConfig.getTextIndex(),textContent);
            }
            //更换图层
            ContourMapLayer contourMapLayer=getContourMapLayer(contourMapType);
            if (contourMapLayer!=null){
                contourMapLayer.drawLayer();
            }
            if (interType.equals(InterType.KIG)){
//                for (int i=0;i<1;i++){
//                    points.remove(0);
//                }
//                points=points.stream().filter(point->point.getVal()>0).collect(Collectors.toList());
                gridAnalyse.kig(points, projectConfig.getGridPath(), projectConfig.getAreaPath(),projectConfig.getMarkTextPath(),projectConfig.getSaveGridPath(),aInfGradeVos );
            }else if (interType.equals(InterType.TIN)){
                gridAnalyse.tin( points,projectConfig.getGridPath(), projectConfig.getAreaPath(),projectConfig.getMarkTextPath(),projectConfig.getSaveGridPath(),aInfGradeVos);
            }
            imgPath = openProject.projectFrameImg(projectConfig.getProjectPath(),projectConfig.getFramePath());
        }catch (Exception e){
            throw e;
        }finally {
            lock.unlock();
        }

        if (imgPath!=null&& !imgPath.isEmpty()){
            byte[] bytesByFile = FileUtil.getBytesByFile(imgPath);
            FileUtil.delete(imgPath);
            if (bytesByFile!=null){
                contourMap=new ContourMap();
                contourMap.setData(bytesByFile);
                boolean insert = MongoUtil.insert(mongoTemplate, contourMap);
                if (!insert){
                    throw new RuntimeException("Mongo 插入数据失败！");
                }
            }

        }
        return contourMap;
    }

    private ContourMapLayer getContourMapLayer(ContourMapType type) {
        ContourMapLayer contourMapLayer=null;
        switch (type){
            //温度统一标准
            case TEMP:contourMapLayer=SpringUtil.getBean(TempContourMapLayer.class);break;
            case MAX_AT:contourMapLayer= SpringUtil.getBean(MaxATContourMapLayer.class);break;
            case MIN_AT:contourMapLayer= SpringUtil.getBean(MinATContourMapLayer.class);break;

            case RAIN_FALL:contourMapLayer= SpringUtil.getBean(RainContourMapLayer.class);break;
            case MAX_RAIN_FALL:contourMapLayer=SpringUtil.getBean(MaxRainContourMapLayer.class);break;

            //风速统一标准
            case MAX_WIND:contourMapLayer=SpringUtil.getBean(MaxWindContourMapLayer.class);break;
            case E_S_WIND:contourMapLayer=SpringUtil.getBean(ESWindContourMapLayer.class);break;

            case VISIBILITY:contourMapLayer=SpringUtil.getBean(VisibilityContourMapLayer.class);break;
            case SNOW_DEPTH:contourMapLayer=SpringUtil.getBean(SnowDepthContourMapLayer.class);break;

        }
        return contourMapLayer;
    }
}
